package edu.wit.acl.service.impl;

import com.alibaba.fastjson.JSONObject;
import edu.wit.acl.entity.Role;
import edu.wit.acl.entity.User;
import edu.wit.acl.service.IndexService;
import edu.wit.acl.service.PermissionService;
import edu.wit.acl.service.RoleService;
import edu.wit.acl.service.UserService;
import edu.wit.common.exception.HgException;
import edu.wit.common.exception.ResultEnums;
import edu.wit.common.result.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
//@Transactional(rollbackFor = Exception.class)
@CacheConfig(cacheNames = "index")
public class IndexServiceImpl implements IndexService {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;

    /**
     * 根据用户名获取用户登录信息
     *
     * @param username
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
//    @Cacheable(key = "#username")
    public Map<String, Object> getUserInfo(String username) {
        Map<String, Object> result = new HashMap<>();
        User user = userService.selectByUsername(username);

        if (null == user) {
            throw new HgException(ResultEnums.AUTH_USER_NOT_FOUND_ERROR);
        }

        //根据用户id获取角色
        List<Role> roleList = roleService.selectRoleByUserId(user.getId());
        List<String> roleNameList = roleList.stream().map(item -> item.getRoleName()).collect(Collectors.toList());
        if (roleNameList.size() == 0) {
            //前端框架必须返回一个角色，否则报错，如果没有角色，返回一个空角色
            roleNameList.add("");
        }

        //根据用户id获取操作权限值
        List<String> permissionValueList = permissionService.selectPermissionValueByUserId(user.getId());

        result.put("userId",user.getId());
        result.put("name", user.getUsername());
        result.put("salt", user.getSalt());
        result.put("roles", roleNameList);
        result.put("ins",user.getIns());
        result.put("category",user.getCategory());
        result.put("permissionValueList", permissionValueList);
        System.out.println("finish_get_userinfo");
        return result;
    }

    /**
     * 根据用户名获取动态菜单
     * @param username
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
//    @Cacheable(key = "'usermenu'")
    public List<JSONObject> getMenu(String username) {
        User user = userService.selectByUsername(username);

        //根据用户id获取用户菜单权限
//        return permissionService.selectPermissionByUserId(user.getId());
        //根据用户id及用户ins获取用户菜单权限
        return permissionService.selectPermissionByUser(user);
    }



}
